﻿using Xejen.Communication.EthernetIP;
using Xejen.Ipc.Framework;
using Xejen.Ipc.Framework.Flows;
using Xejen.Ipc.Framework.Steps;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xejen.Ipc.Test.Steps
{
    /// <summary>
    /// 表示单元1这个步骤
    /// </summary>
    public class Unit1 : IStepBody<Data>
    {
        private bool _locked;

        /// <inheritdoc/>
        public async Task ExecuteAsync(IFlowExecutionContext<Data> context)
        {
            Debug.WriteLine($"------------进入：单元1------------");

            Data data = context.Data;
            data.Value = new Random().Next(0, 20);

            //Convert.ToInt32("Fsa");

            //_ = Task.Run(async () =>
            //{
            //    await EipMethod();
            //});


            lock (typeof(object))
            {
                if (_locked)
                {
                    return;
                }
                _locked = true;
            }

            await Task.Run(async () =>
            {
                var wrapper = new EthernetIpAddressWrapper
                {
                    RequestAddress = new Communication.Endpoints.Address<EthernetIpAddress>
                    {
                        Value = new EthernetIpAddress
                        {
                            Tag = "InInt"
                        }
                    }
                };
                await context.Data.EthernetIpCommunicator.WriteShortAsync(wrapper, 123);
            }).ConfigureAwait(false);

            _locked = false;

            await Task.CompletedTask;
        }

        public async Task EipMethod()
        {
            // 模拟异步访问Ethernet/IP方法，此处替换为您的实际代码
            await Task.Delay(3000); // 10秒钟
        }
    }
}
